<template>
  <div class="msg-container">
    <!-- 左侧好友列表 -->
    <div class="friend-list">
      <div class="search-box">
        <input v-model="searchKeyword" placeholder="搜索" class="search-input">
      </div>
      <div v-if="filteredFriends.length === 0" class="empty-tip">
        暂无相关聊天记录
      </div>
      <div v-for="friend in filteredFriends" :key="friend.receiverId" class="friend-item"
        :class="{ selected: isSelected(friend.receiverId) }" @click="enterChat(friend)">
        <div class="avatar-container">
          <img :src="friend.avatar" class="avatar">
          <span class="online-status1" v-if="friend.online"></span>
        </div>
        <div class="info">
          <div class="name-line">
            <span class="name">{{ friend.name }}</span>
            <span class="time">{{ friend.time }}</span>
          </div>
          <div class="msg-line">
            <span class="last-msg">{{ friend.lastMsg }}</span>
            <span v-if="messageStore.unreadMap[friend.receiverId] > 0" class="unread-bubble">
              {{ messageStore.unreadMap[friend.receiverId] }}
            </span>
          </div>
        </div>
      </div>
    </div>

    <!-- 右侧区域 -->
    <div class="right-panel">
      <!-- 动态顶部状态栏 -->
      <div class="header">
        <!-- 聊天页头部 -->
        <div v-if="isChatPage" class="chat-header">
          <img :src="currentChatInfo.avatar" class="avatar">
          <div class="user-info">
            <div class="name">{{ currentChatInfo?.name }}</div>
            <span class="online-status2" v-if="currentChatInfo?.online == '1'"></span>
            <div class="status">{{ currentChatInfo?.online == '1' ? '在线' : '离线' }}</div>
          </div>
        </div>

        <!-- 默认头部 -->
        <div v-else class="default-header">
          <div class="status">
            <span>未读总数：{{ messageStore.totalUnread }}</span>
          </div>
        </div>
      </div>

      <!-- 嵌套路由视图 -->
      <div class="router-view">
        <RouterView />
      </div>

    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, onUnmounted, computed, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { connectWebSocket } from '@/services/WebSocketService'
import { getFriendList } from '@/api/Mmp/message'
import { useMessageStore } from '@/store/messageStore'

const messageStore = useMessageStore();

//好友列表类型
interface FriendItem {
  receiverId: number
  online: number
  name: string
  avatar: string
  lastMsg: string
  time: string
}

const router = useRouter()
const friends = ref<FriendItem[]>([])


// 选中状态判断
const isSelected = (receiverId: number) => {
  return route.params.receiverId === String(receiverId)
}

// 搜索功能
const searchKeyword = ref('')
const filteredFriends = computed(() => {
  return friends.value.filter(friend =>
    friend.name.includes(searchKeyword.value) ||
    friend.lastMsg.includes(searchKeyword.value)
  )
})

// 路由相关
const route = useRoute()
const isChatPage = computed(() => route.path.includes('/chat'))
const currentChatInfo = computed(() => ({
  avatar: route.query.avatar,
  name: route.query.name,
  online: route.query.online
}))



// 初始化数据
const fetchFriends = async () => {
  getFriendList().then((result) => {
    // 将服务端未读数与 store 状态合并
    friends.value = result.data.msgUserList;
    result.data.msgUserList.forEach(friend => {
      messageStore.unreadMap[friend.receiverId] = friend.unread;
    });
    messageStore.totalUnread = result.data.unreadCount
  }).catch(() => {
    console.log('获取好友列表失败！')
  })
}

// 时间格式化函数
const formatMessageTime = (timeString: string): string => {
  const targetDate = new Date(timeString);
  const now = new Date();

  const pad = (n: number) => n.toString().padStart(2, '0');

  const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
  const targetDay = new Date(targetDate.getFullYear(), targetDate.getMonth(), targetDate.getDate());

  if (targetDay.getTime() === today.getTime()) {
    return `${pad(targetDate.getHours())}:${pad(targetDate.getMinutes())}`;
  }

  const yesterday = new Date(today);
  yesterday.setDate(yesterday.getDate() - 1);
  if (targetDay.getTime() === yesterday.getTime()) {
    return `昨天 ${pad(targetDate.getHours())}:${pad(targetDate.getMinutes())}`;
  }

  const year = targetDate.getFullYear();
  const month = pad(targetDate.getMonth() + 1);
  const day = pad(targetDate.getDate());
  return `${year}/${month}/${day} ${pad(targetDate.getHours())}:${pad(targetDate.getMinutes())}`;
};

const handleNewMessage = (message: any) => {

  const index = friends.value.findIndex(f => f.receiverId == message.senderId)
  if (index > -1) {
    // 使用 splice 触发响应式更新
    friends.value.splice(index, 1, {
      ...friends.value[index],
      lastMsg: message.content,
      time: formatMessageTime(message.time),
    })
    messageStore.totalUnread++;
  }



  if (message.senderId !== 'system' && !isSelected(message.senderId)) {
    console.log("更新sore中的列表信息！")
    // 更新 store 中的未读数
    messageStore.incrementUnread(message.senderId)
  }
}


onMounted(() => {
  window.$eventBus?.on('message-received', handleNewMessage);
  connectWebSocket()
  fetchFriends()
});

onUnmounted(() => {
  window.$eventBus?.off('message-received', handleNewMessage);
});

const enterChat = (friend: FriendItem) => {
  messageStore.totalUnread = messageStore.totalUnread - messageStore.unreadMap[friend.receiverId] >= 0 ? messageStore.totalUnread - messageStore.unreadMap[friend.receiverId] : 0;
  messageStore.resetUnread(friend.receiverId)
  router.push({
    path: `/Mmp/message/chat/${friend.receiverId}`,
    query: {
      name: friend.name,
      avatar: friend.avatar,
      receiverId: friend.receiverId,
      online: friend.online
    }
  })
}
</script>

<style scoped>
* {
  padding: 0;
  margin: 0;
}


.router-view {
  height: 90%;
}

.search-box {
  justify-self: center;
  place-content: center;
  height: 8%;
}

.search-input {
  background: #f0f0f0;
  padding: 8px 15px;
  border-radius: 10px;
}

.friend-list {
  min-width: 200px;
  width: 20%;
  height: 100%;
  border-right: 1px solid #e0e0e0;
  background: #fafafa;
}

.friend-list>div:last-child {
  flex: 1;
  overflow-y: auto;
}

/* 好友项选中状态 */
.friend-item.selected {
  background: #e6f3ff !important;
  position: relative;
  overflow: hidden;
}

.friend-item.selected::after {
  content: "";
  position: absolute;
  right: -1px;
  top: 0;
  bottom: 0;
  width: 2px;
  background: #1890ff;
}

/* 调整头部样式 */
.header {
  height: 8%;
  padding: 0 20px;
  background: #f8f8f8;
  border-bottom: 1px solid #e0e0e0;
  display: flex;
  align-items: center;
}

.chat-header {
  display: flex;
  align-items: center;
  gap: 12px;
}

.avatar-container {
  position: relative;
  display: inline-block;

  .avatar {
    width: 38px;
    height: 45px;
    border-radius: 4px;
  }
}

.online-status1 {
  position: absolute;
  bottom: 2px;
  /* 调整位置靠近头像底部 */
  right: 2px;
  /* 调整位置靠近头像右侧 */
  width: 10px;
  height: 10px;
  background: #67c23a;
  /* 绿色 */
  border: 2px solid #fff;
  /* 白色边框，避免与背景混淆 */
  border-radius: 50%;
}

.online-status2 {
  position: absolute;
  top:73px;
  width: 10px;
  height: 10px;
  background: #67c23a;
  /* 绿色 */
  border: 2px solid #fff;
  /* 白色边框，避免与背景混淆 */
  border-radius: 50%;
}

.chat-header .avatar {
  width: 38px;
  height: 45px;
  border-radius: 4px;
}

.user-info .name {
  font-size: 16px;
  font-weight: 500;
}

.user-info .status {
  margin-left: 15px;
  font-size: 12px;
  color: #666;
}

.default-header {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.msg-container {
  display: flex;
  width: 100%;
  height: 75vh;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  margin-bottom: -1.2%;
}


.right-panel {
  flex: 1;
  min-width: 500px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

/* 保证路由视图填充剩余空间 */
:deep(.chat-container) {
  flex: 1;
  overflow: hidden;
}

.friend-item {
  display: flex;
  padding: 12px;
  cursor: pointer;
}

.friend-item:hover {
  background: #f5f5f5;
}

.avatar {
  width: 48px;
  height: 48px;
  border-radius: 6px;
  margin-right: 12px;
}

.info {
  flex: 1;
  min-width: 0;
}

.name-line {
  display: flex;
  justify-content: space-between;
  margin-bottom: 4px;
}

.name {
  font-size: 16px;
  color: #000;
}

.time {
  font-size: 12px;
  color: #888;
}

.msg-line {
  display: flex;
  justify-content: space-between;
}

.last-msg {
  font-size: 14px;
  color: #666;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.unread-bubble {
  background: #f56c6c;
  color: white;
  border-radius: 10px;
  padding: 2px 8px;
  font-size: 12px;
}
</style>